import React from 'react';
import { Card } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import Search from './components/IndexSearch';
import AddModal from './components/IndexAddModal';
import { pageList, del} from '@/services/Budget';
import {indexColumns as columns} from './columns';
import { useModel } from 'umi';

class Budget extends React.Component {
  constructor(props) {
    super(props)
    this.proTableRef = React.createRef();
    this.unitId = props.id;
    this.state = {
      params: {unitId: props.id},
      dataSource: []
    }
  }

  /* 获取table列表数据 */
  getPageList = async (currentParams) => {
    try {
      const params = this.state.params;
      const res = await pageList({
        ...params,
        ...currentParams
      })
      this.setState({dataSource: res.data})
      return {
        success: true,
        data: res.data,
        total: res.totalSize
      }
    } catch (e) {
      console.error(e)
    }
  }

  /* 监听查询事件 */
  onSearch = (data) => {
    const params = this.state.params;
    this.setState({params: {...params, ...data}});
    this.proTableRef.current.reload();
  }

  /* 刷新事件 */
  onReload = () => {
    const unitId = this.unitId;
    this.setState({params: {unitId}});
    this.proTableRef.current.reload();
  }

  /* 监听删除项 */
  onDel = async (id) => {
    const dataSource = this.state.dataSource;
    this.setState({dataSource: dataSource.filter(function (item) {
      return item.id !== id
    })})
    await del(id);
    // this.proTableRef.current.reload();
  }

  render() {
    const proTableRef = this.proTableRef;
    const dataSource = this.state.dataSource;
    return (
      <PageContainer>
        <Card
          title="预算列表"
          bordered={false}
          bodyStyle={{ paddingTop: 30, paddingBottom: 0 }}>
          <Search search={this.onSearch} reset={this.onReload}/>
        </Card>
        <ProTable
          actionRef={proTableRef}
          rowKey='id'
          headerTitle={<AddModal add={this.onReload}>分拨预算</AddModal>} 
          search={false}
          dataSource={dataSource}
          columns={columns(this.onDel)}
          request={this.getPageList} />
      </PageContainer>
    )
  }
}

const Main = () => {
  const { initialState } = useModel('@@initialState');
  const unitId = initialState.currentUser.unitId;
  return (
    <Budget id={unitId}/>
  )
}

export default Main